/**
 * Created by Toma on 2016-8-9 11:24:22
 * 量化积木 - @ver 0.0.1
 */
var cc = window.cc || {};
cc.pro = new function () {
  "use strict";
  var self = this;

  /**
   * ====================================================================
   * 1.策略市场
   * ====================================================================
   */
  self.market = function () {
    // 点击搜索框
    $('.ui-searchbar').tap(function (e) {
      if (e.target.className === 'ui-icon-close') {
        $('#search').val('');
        $('.ui-searchbar-wrap').removeClass('focus');
      } else {
        $('.ui-searchbar-wrap').addClass('focus');
        $('.ui-searchbar-input input').focus();
      }
    });
    // TODO 搜索全文
    $('.ui-searchbar-cancel').tap(function () {
      var data = $('#search').val();
      self.searchData('.cl-list', {key: data}, 'data/test2.json', function (data) {
        seq(data, true);
      });
    });

    // 小折线图
    $(window).on('load', function () {
      self.minline('.J_can');
    });

    /**
     * TODO 加载更多 链接后台数据
     * @param num 自增 请求的页数
     * @param load 避免反复请求
     */
    var num = 1;
    var load = true;
    self.roll.on('scrollEnd', function () {
      this.y - 100 <= this.maxScrollY && load && $.ajax({
        url: 'data/test2.json',
        type: 'get',
        data: {num: num},
        dataType: 'json',
        beforeSend: function () {
          $('.cl-con').append('<div class="ui-loading-wrap"><p>加载中</p><i class="ui-loading"></i></div>');
          self.roll.refresh();
          load = false;
        },
        success: function (data) {
          $('.cl-con .ui-loading-wrap').remove();
          seq(data, false);
          load = true;
          num++;
        },
        error: function (err) {
          $('.cl-con .ui-loading-wrap').remove();
          alert('错误代码' + err.readyState);
          self.roll.refresh();
          load = true;
        }
      });
    });

    // 填充数据
    function seq(data, sch) {
      // @param isend -> 为真表示没有数据
      if (!data.isend) {
        var html = [];
        var cl = $('.cl-list');
        var model =
            '<li class="ui-border-t"><div class="ui-flex">' +
            '<div class="cc-ord"><strong class="ui-border">_no_</strong></div>' +
            '<div class="ui-list-info cl-list-con">' +
            '<h4 class="ui-nowrap"><span class="pull-right">_id_</span> _title_</h4>' +
            '<p class="ui-nowrap"><span class="pull-right">粉丝数量：_fans_</span><span>创建人：_user_</span></p>' +
            '</div><div class="cl-char ui-border"><canvas class="_J_can_" data-lin="_data_"></canvas></div>' +
            '</div><div class="cl-table">' +
            '<table class="ui-table ui-border"><thead><tr><th>策略次数</th><th>策略胜率</th><th>策略收益</th><th>策略回撤</th></tr></thead>' +
            '<tbody><tr><td>_Lcs_</td><td>_Lsl_</td><td>_Lsy_</td><td>_Lhc_</td></tr></tbody>' +
            '</table></div><div class="ui-flex ui-flex-pack-end cl-i-link">' +
            '<a href="_jl_"><span>&#xf621;</span> 交易记录</a>' +
            '<a href="_xq_"><span>&#xf625;</span> 策略详情</a></div></li>';

        $.each(data.com, function (i, el) {
          html[i] = model.replace(/_no_/, el.no)
              .replace(/_title_/, el.title)
              .replace(/_id_/, el.id)
              .replace(/_fans_/, el.fans)
              .replace(/_user_/, el.user)
              .replace(/_data_/, el.data)
              .replace(/_Lcs_/, el.list.cs)
              .replace(/_Lsl_/, el.list.sl)
              .replace(/_Lsy_/, el.list.sy)
              .replace(/_Lhc_/, el.list.hc)
              .replace(/_jl_/, el.jl)
              .replace(/_xq_/, el.xq)
              .replace(/_J_can_/, 'J_can_' + num);
        });
        !sch ? cl.append(html.join('')) : cl.html(html.join(''));
        self.minline('.J_can_' + num);
      } else {
        $('.cl-con .data-end').remove();
        $('.cl-con').append('<div class="data-end">- 没有数据了 -</div>');
      }
      self.roll.refresh();
    }

  };


  /**
   * ====================================================================
   * 2.策略详情
   * ====================================================================
   */
  self.detail = function (data) {
    // 图表
    self.dataline(data);
  };


  /**
   * ====================================================================
   * 3.策略配置
   * ====================================================================
   */
  self.configuration = function () {
    // 选择配置项
    // 默认页面为code
    var page = 'code';
    $('.cc-a-item').on('tap', function () {
      $(this).addClass('active').siblings().removeClass('active');
      var tag = $(this).data('targ');
      $('#' + tag).show().siblings('.cl-page').hide();
      self.roll.refresh();
      page = tag;
    });


    // 风控参数
    var fx = {zs: false, zy: false};
    self.fkcs(function () {
      // 止损
      jud($('#ctrZs'), $('#formZs'), 'zs');
      // 止盈
      jud($('#ctrZy'), $('#formZy'), 'zy');

      function jud(ctr, fm, tit) {
        ctr.find('input').prop('checked') ? function () {
          fm.val(parseInt(ctr.find('.J_num').html()));
          fx[tit] = true;
        }() : function () {
          fm.val(0);
          fx[tit] = false;
        }();
        $('.J_fxkz_tit').html(function () {
          if (fx.zs && fx.zy) {
            return '止损+止盈';
          } else if (fx.zs) {
            return '止损';
          } else if (fx.zy) {
            return '止盈';
          } else {
            return '未选择';
          }
        });
      }
    });


    // 开启消息提醒
    $('.J_warn').on('tap', function () {
      var ini = $(this).find('input'),
          ckd = ini.prop('checked'),
          tit = $('.J_warntit'),
          fmi = $('#formWarn');
      ckd ? (tit.html('关') && fmi.val(0)) : (tit.html('开') && fmi.val(1));
      ini.prop('checked', !ckd);
    });


    // 搜索股票代码
    $('#sehcode').on('keyup', function () {
      var model = '<li class="ui-border-t"><p>_con_</p></li>';
      var data = {
        type: 'code',
        value: this.value
      };
      // TODO 添加后台链接
      self.searchData('.J_sehcode_aim', data, 'data/test3.json', function (data) {
        var html = [];
        $.each(data.con, function (i, el) {
          html.push(model.replace(/_con_/, el));
        });
        $('.J_sehcode_aim').html(html.join(''));
        self.roll.refresh();
      });
    });
    // 添加更新股票代码
    $('.J_sehcode_aim').on('tap', 'li', function () {
      var txt = $(this).find('p').html();
      $(this).addClass('active').siblings().removeClass('active');
      $('.J_code_tit').html(txt);
      $('#formCode').val(txt);
    });


    // 搜索股票则时
    $('#sehtime').on('keyup', function () {
      var model = '<li class="ui-border-t"><p>_con_</p></li>';
      var data = {
        type: 'time',
        value: this.value
      };
      // TODO 添加后台链接
      self.searchData('.J_sehtime_aim', data, 'data/test3.json', function (data) {
        var html = [];
        $.each(data.con, function (i, el) {
          html.push(model.replace(/_con_/, el));
        });
        $('.J_sehtime_aim').html(html.join(''));
        self.roll.refresh();
      });
    });
    // 添加更新股票则时
    $('.J_sehtime_aim').on('tap', 'li', function () {
      var txt = $(this).find('p').html();
      $(this).addClass('active').siblings().removeClass('active');
      $('.J_time_tit').html(txt);
      $('#formTime').val(txt);
    });


    // 加载更多数据
    var mod = {code: 1, time: 1};
    var load = true;
    self.roll.on('scrollEnd', function () {
      this.y - 100 <= this.maxScrollY && load && function () {
        var per = page == 'code' || page == 'time';
        per && $.ajax({
          url: 'data/test3.json?type=' + page + '&num=' + mod[page],
          type: 'get',
          dataType: 'json',
          beforeSend: function () {
            $('.J_scroll').append('<div class="ui-loading-wrap"><p>加载中</p><i class="ui-loading"></i></div>');
            self.roll.refresh();
            load = false;
          },
          success: function (data) {
            $('.J_scroll .ui-loading-wrap').remove();
            seq(data);
            load = true;
            mod[page]++;
          },
          error: function (err) {
            $('.J_scroll .ui-loading-wrap').remove();
            alert('错误代码' + err.readyState);
            self.roll.refresh();
            load = true;
          }
        });

        var model = '<li class="ui-border-t"><p>_con_</p></li>';

        function seq(data) {
          var html = [];
          $.each(data.con, function (i, el) {
            html.push(model.replace(/_con_/, el));
          });
          $('.J_seh' + page + '_aim').append(html.join(''));
          self.roll.refresh();
        }
      }();
    });


    // 提交表单
    $('#yhsub').on('tap', function () {
      var vl = true;
      if (!document.form.name.value) {
        layer.open({content: '请输入策略名称'});
        vl = false;
      }
      if (!document.form.time.value) {
        layer.open({content: '请选择股票时间'});
        vl = false;
      }
      if (!document.form.code.value) {
        layer.open({content: '请选择股票代码'});
        vl = false;
      }
      vl && function () {
        var data = $('#form').serialize();
        var load;
        $.ajax({
          type: 'get',
          url: 'data/test1.json',
          data: data,
          dataType: 'json',
          beforeSend: function () {
            load = $.loading({content: '努力提交中...'});
          },
          success: function () {
            load.loading("hide");
          },
          error: function () {
            load.loading("hide");
          }
        });
      }();
    });

  };


  /**
   * ====================================================================
   * 4.策略优化
   * ====================================================================
   */
  self.optimization = function (data) {
    // 风控参数
    self.fkcs();
    // 图表
    self.dataline(data);
    // 点击应用
    $('#use').on('tap', function () {
      layer.open({
        title: '股票数',
        shadeClose: false,
        content: '<input type="number" class="pluint" placeholder="请输入股票数"/>',
        btn: ['确定', '取消'],
        yes: function (index) {
          alert('1');
          layer.close(index);
        }
      });
    });

    // 点击测试
    $('#test').on('tap', function () {
      var load;
      var data = {};
      // TODO 链接后台数据
      $.ajax({
        url: 'data/test1.json',
        type: 'get',
        data: data,
        dataType: 'json',
        beforeSend: function () {
          load = $.loading({content: '努力加载中...'});
        },
        success: function (seq) {
          load.loading("hide");
          self.dataline(seq);
          self.roll.scrollTo(0, 20, 200);
        },
        error: function () {
          load.loading("hide");
          alert('错误代码' + err.readyState);
        }
      });
    });

  };


  /**
   * ====================================================================
   * 5.我的策略
   * ====================================================================
   */
  self.mine = function () {
    // 策略控制台方法
    var clcon = {
      // 开始
      start: function (ele, id) {
        if ($(ele).hasClass('action')) {
          this.inter({id: id, handle: 'end'}, function () {
            $(ele).removeClass('action').find('span').html('&#xf632;');
            $.tips({
              content: '已停止运行',
              stayTime: 1200,
              type: "success"
            })
          });
        } else {
          this.inter({id: id, handle: 'start'}, function () {
            $(ele).addClass('action').find('span').html('&#xf630;');
            $.tips({
              content: '启动成功',
              stayTime: 1200,
              type: "success"
            })
          });
        }
      },
      // 停止
      end: function (ele, id) {
        $(ele).prev().hasClass('action') && this.inter({id: id, handle: 'end'}, function () {
          $(ele).prev().removeClass('action').find('span').html('&#xf632;');
          $.tips({
            content: '已停止运行',
            stayTime: 1200,
            type: "success"
          })
        });
      },
      // 分享
      share: function () {
        console.log('分享~');
      },
      // 删除
      delete: function (ele, id) {
        var that = this;
        layer.open({
          title: false,
          content: '<i class="ui-icon-warn-block"></i>确定删除',
          btn: ['确定', '取消'],
          yes: function (index) {
            that.inter({id: id, handle: 'delete'}, function () {
              layer.close(index);
              $('#' + id).hide();
              $.tips({
                content: '删除成功~',
                stayTime: 1200,
                type: "success"
              })
            });
          }
        });
      },
      /**
       * TODO 与后台交互
       * @param data -> id: 策略ID -> handle: 命令
       * @param callback 请求成功后的回调
       */
      inter: function (data, callback) {
        var load;
        $.ajax({
          url: 'data/test1.json',
          type: 'get',
          data: data,
          dataType: 'json',
          beforeSend: function () {
            load = $.loading({content: '努力加载中...'});
          },
          success: function () {
            load.loading("hide");
            callback();
          },
          error: function (err) {
            load.loading("hide");
            alert('错误代码' + err.readyState);
          }
        });
      }
    };

    // 策略控制台
    $('.J_console').on('tap', function (e) {
      var js = $(e.target).data('js'),
          id = $(this).parent().attr('id');
      js && clcon[js](e.target, id);
    });

  };


  /**
   * ====================================================================
   * main
   * ====================================================================
   */
  self.roll = '';
  self._init = function () {
    // 使用IScroll滑动
    self.roll = new IScroll('#wrapper', {
      click: true,
      mouseWheel: true,
      freeScroll: true
    });
    document.addEventListener('touchmove', function (e) {
      e.preventDefault();
    }, false);

  }();


  /**
   * 风控参数
   */
  self.fkcs = function (callback) {
    $('.J_check').on('tap', function (e) {
      var Ini = $(this).find('.J_num'),
          num = parseInt(Ini.html()),
          cdIni = $(this).find('input'),
          ckd = cdIni.prop('checked');

      if (ckd) {
        if ($(e.target).is('.J_add')) {
          num < 100 && Ini.html(num + 1 + '%');
        } else if ($(e.target).is('.J_sub')) {
          num > 1 && Ini.html(num - 1 + '%');
        } else {
          cdIni.prop('checked', false);
          $(this).removeClass('active');
        }
      } else {
        cdIni.prop('checked', true);
        $(this).addClass('active');
      }
      callback && callback();
    });
  };


  // 测试计数器
  (function (){
    var um = 0;
    var caot;
    var co_add = {
      'touchstart': function () {
        var loop = function () {
          $('.J_testmark').html(um++);
          caot = setTimeout(loop, 50);
        };
        loop();
      },
      'touchend':function () {
        clearTimeout(caot);
      }
    };
    var co_sub = {
      'touchstart': function () {
        var loop = function () {
          $('.J_testmark').html(um--);
          caot = setTimeout(loop, 50);
        };
        loop();
      },
      'touchend':function () {
        clearTimeout(caot);
      }
    };
    $('.active').on(co_add);
    $('.cc-footer li:nth-child(2)').on(co_sub);
  })();
  

  /**
   * echar 数据表
   * @param data
   */
  self.dataline = function (data) {
    var eChart = echarts.init(document.getElementById('echar'));
    var option = {
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: data.time
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: '{value} '
        }
      },
      series: [
        {
          name: '业绩',
          type: 'line',
          data: data.data,
          markLine: {
            data: [
              {type: 'average', name: '平均值'}
            ]
          }
        }
      ]
    };

    eChart.setOption(option);
  };


  /**
   * 迷你折线图
   * @param cl 钩子
   */
  self.minline = function (cl) {
    $(cl).each(function (i, el) {
      var data = $(el).data('lin').split(',').map(function (i) {
            return parseInt(i)
          }),
          coW = $(el).width(),
          coH = $(el).height();

      el.width = coW;
      el.height = coH;

      var ctx = el.getContext('2d'),
          max = Math.max.apply(null, data),
          min = Math.min.apply(null, data),
          zh = max - min,
          hLen = coH / zh,
          wLen = coW / (data.length - 1);

      ctx.beginPath();
      ctx.lineWidth = 1;
      ctx.lineCap = 'round';
      ctx.lineJoin = 'round';
      ctx.strokeStyle = 'red';

      data.forEach(function (el, i) {
        ctx.lineTo(i * wLen, (zh - (el - min)) * hLen);
      });

      ctx.stroke();
    });
  };

  /**
   * 关键字搜索，并将返回结果插入到页面中
   * @param aim 数据插入目标
   * @param dt 搜索关键字
   * @param url 提交地址
   * @param callback
   */
  self.searchData = function (aim, dt, url, callback) {
    $.ajax({
      url: url,
      type: 'get',
      data: dt,
      dataType: 'json',
      beforeSend: function () {
        $(aim).html('<div class="ui-loading-wrap"><i class="ui-loading"></i></div>');
      },
      success: function (data) {
        callback(data);
      },
      error: function (err) {
        $(aim).html('错误代码' + err.readyState);
      }
    });
  };

};
